
package com.czl.project.initialize;

import io.lettuce.core.RedisBusyException;
import io.lettuce.core.RedisException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.connection.stream.ReadOffset;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * 初始化短链接监控消息队列消费者组
 */
@Component
@RequiredArgsConstructor
public class ShortLinkStatsStreamInitializeTask implements InitializingBean {

    private final StringRedisTemplate stringRedisTemplate;

    @Value("${spring.data.redis.channel-topic.short-link-stats}")
    private String topic;
    @Value("${spring.data.redis.channel-topic.short-link-stats-group}")
    private String group;
    @Override
    public void afterPropertiesSet() {
        try {
            stringRedisTemplate.opsForStream()
                    .createGroup(topic, ReadOffset.latest(), group);
        } catch (RedisSystemException e) {
            Throwable rootCause = e.getRootCause();
            if (rootCause instanceof RedisBusyException) {
                // group 已存在，无需处理
                return;
            } else if (rootCause instanceof RedisException && e.getMessage().contains("NOGROUP")) {
                // stream 不存在，先添加 dummy 数据初始化
                stringRedisTemplate.opsForStream().add(topic, Map.of("init", "true"));
                // 再次尝试创建 group
                stringRedisTemplate.opsForStream()
                        .createGroup(topic, ReadOffset.latest(), group);
            } else {
                throw e;
            }
        }
    }
}
